package cn.wj.base.util;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import cn.wj.base.annotation.Transactional;
import cn.wj.base.util.Advice;
import cn.wj.base.util.DBPool;
import cn.wj.base.util.ThreadLocalContext;

public class AdviceImp extends Advice {
	private Connection connection = DBPool.getInstance().getConnection();
	private boolean Tran = false;

	public void start() {
		Method method = getMethod();
		if (method.isAnnotationPresent(Transactional.class)) {
			Tran = true;
		}
		try {
			if (Tran) {
				connection.setAutoCommit(false);
			}
			ThreadLocalContext.getInstance().bind(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void end() {
		if (Tran) {
			try {
				connection.commit();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void error() {
	}

	@Override
	public void must() {
		ThreadLocalContext.getInstance().remove();
	}
}
